let wx_code = getParam("code")
let access_token = "" //访问token/
let ticket = "" //应用ticket
let url = "http://zipapp/ZNWD/common/index.html"
$(function () {
	if (wx_code) {
		// alert("wx_code:" + wx_code)
		// $("#output").html(wx_code)
	}
})


function getParam(variable) {
	let query = window.location.search.substring(1);
	let vars = query.split("&");
	for (let i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1]
		}
	}
	return ''
}

//1   获取微信code
function getWxCode() {
	$("#showP").html("正在初始化...")
	//首先判断是否存在
	if (!wx_code) {
		var sURL = sURLgetWxCode;
		sURL += 'appid=' + appid;
		sURL += '&redirect_uri=' + encodeURIComponent(encodeURIComponentUrl);
		sURL += '&response_type=code';
		sURL += '&scope=SCOPE';
		sURL += '&state=STATE';
		sURL += 'agentid=' + magentid;
		sURL += '#wechat_redirect';
		location.href = sURL;
	} else {
		$("#showP").html("初始化失败")
	}
}

let  judgeCode = setInterval(() => {
	console.log(999)
	if (wx_code) {
		window.clearInterval(judgeCode);
		if (isFlag) {
			// 开发模式直接跳过
			let data = {
				CODE: wx_code,
				appId: "1000469"
			}
			data = JSON.stringify(data);
			$.ajax({
				url: "http://27.10.115.223:10443/igwmobile/proxy/getUserByIgwCode",
				type: "post",
				// async: true, //是否同步，false表示同步请求
				dataType: "json",
				data: data,
				headers: {
					"Content-Type": "application/json;charset=UTF-8",
				},
				success: function (res, txt, xhr) {
					if(res.code == "100001" ) {
						getAuthentication(res.data)
					} else {
						$("#showP").html("登录失败," + "用户信息获取为空")
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$("#showP").html("登录失败," + "用户信息获取为空")
				}
			})
		} else {
			// 生产模式 需要text.js 中的iscp 然后在掉业务
			// 微信注册
			createISCPLink("2021128")
			setTimeout(iscpInit, 3000)
			let dingTime = setInterval(() => {
				if (sessionStorage.getItem("err_msg")) {
					let data = {
						CODE: wx_code,
						appId: "1000469"
					}
					data = JSON.stringify(data);
					$.ajax({
						url: "https://id.sgcc.com.cn:10443/igwmobile/proxy/getUserByIgwCode",
						type: "post",
						// async: true, //是否同步，false表示同步请求
						dataType: "json",
						data:data,
						headers: {
							"Content-Type": "application/json;charset=UTF-8",
						},
						success: function (res, txt, xhr) {
							if(res.code == "100001" ) {
								getAuthentication(res.data)
							} else {
								$("#showP").html("登录失败," + "用户信息获取为空")
							}
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							$("#showP").html("登录失败," + "用户信息获取为空")
						}
					})
					
					window.clearInterval(dingTime);
				} else {
	
				}
			}, 500)
		}
	} else {	
	}
}, 500)
// 获取个人信息   请求头
function getAuthentication(data) {
	$("#showP").html("正在登录...")
	const { publicKey, privateKey } = sm2.generateKeyPairHex();
	sessionStorage.setItem("fpuk", publicKey)
	sessionStorage.setItem("fprk", privateKey)
	if (sessionStorage.getItem("iscp_port")) {
		iscp_port = sessionStorage.getItem("iscp_port");
	} else {
		iscp_port = ""
	}
	let timestamp = Date.now() + "";
	let pppp = {
		"code": data,
		"time": timestamp
	}
	pppp = JSON.stringify(pppp)
	let dddd = sm3(pppp)
	let fpuk = sessionStorage.getItem("fpuk")
	$.ajax({
		url: localUrlLink + iscp_port + "/document/isc/acceptParam",
		type: "post",
		async: true, //是否同步，false表示同步请求
		dataType: "json",
		contentType: 'application/json',
		data: pppp,
		headers: {
			sign: dddd,
			fpuk: fpuk
		},
		success: function (res, txt, xhr) {
			let Authentication = xhr.getResponseHeader("Authentication")
			let bpuk = xhr.getResponseHeader("bpuk")
			if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
				if (Authentication && bpuk) {
					if (res.code == 200) {
						$("#showP").html("登录成功")
						sessionStorage.setItem("Authentication", Authentication);
						// 用户id
						sessionStorage.setItem("userId", res.resultValue.userId);
						// 邮箱
						sessionStorage.setItem("toMail", res.resultValue.email);
						// 单位id
						sessionStorage.setItem("unitId", res.resultValue.unitId);
						// 后公钥
						sessionStorage.setItem("bpuk", bpuk)
						// 用户名
						sessionStorage.setItem("userName", res.resultValue.name);
					
						let isAgreement = res.resultValue.isAgreement;
						if (sessionStorage.getItem("userId") && sessionStorage.getItem("userName") && sessionStorage.getItem("Authentication")) {
							// addOperator(1, 1, "登录", 1)
							if (isAgreement == "true") {
								$(location).attr("href", "./common/Home.html");
							} else {
								$(location).attr("href", "./common/index1.html");
							}
						}
					} else if (res.code == 500) {
						$("#showP").html("登录失败," + res.resultValueStr)
					} else {
						$("#showP").html("登录失败,"+ res.resultValueStr)
					}
				} else {
					$("#showP").html("登录失败," + res.resultValueStr)
				}
			} else {
				$("#showP").html("登录失败, 完整性校验失败！")
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#showP").html("登录请求失败")
		}
	});
}
getWxCode();
// getIscToken();